package com.chezhujie.www.controller.admin;



import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;




import com.chezhujie.www.controller.BaseController;
import com.chezhujie.www.core.page.Pagination;
import com.chezhujie.www.domain.Czjbusiness;
import com.chezhujie.www.domain.Tsuser;
import com.chezhujie.www.domain.Tuserrole;
import com.chezhujie.www.security.BadCredentialsException;
import com.chezhujie.www.security.UsernameNotFoundException;
import com.chezhujie.www.service.CzjbusinessService;
import com.chezhujie.www.service.TroleService;
import com.chezhujie.www.service.TuserService;
import com.chezhujie.www.service.TuserroleService;
import com.chezhujie.www.utils.ConvertObj;
import com.chezhujie.www.web.CookieUtils;
import com.chezhujie.www.web.RequestUtils;




import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;


@Controller
@RequestMapping(value="sys")
public class TuserController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(TuserController.class);
	public static final String COOKIE_ERROR_REMAINING = "_error_remaining";
	public static final String RETURN_URL = "returnUrl";
	public static final String MESSAGE = "message";
	public static final String AUTH_KEY = "auth_key";
	public static final String MEMBER_KEY = "member_key";
	public TuserController() {
	}
 

	@RequestMapping(value = "/logout.do")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		Object auth = request.getSession().getAttribute(AUTH_KEY);
		if (auth != null) {
		/*	request.getSession().invalidate();*/
			Tsuser user=(Tsuser) auth;
			user.setPasswd(null);
			user.setLastlogintime(new Date());
			tuserService.updateTuser(user);
			request.getSession().removeAttribute(AUTH_KEY);
		}
		String returnUrl = RequestUtils.getQueryParam(request, RETURN_URL);
		String view = getView(returnUrl);
		if (view != null) {
			return view;
		} else {
			return "redirect:login.do";
		}
	}

	/**
	 * 登陆页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login.do", method = RequestMethod.GET)
	public String login(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {

//		LanguageCookie.set(resolver,request, model);//语言切换并设置
		String returnUrl = RequestUtils.getQueryParam(request, RETURN_URL);
		String message = RequestUtils.getQueryParam(request, MESSAGE);
		Object auth = request.getSession().getAttribute(AUTH_KEY);
		if (auth != null) {
			// 存在认证ID
			String view = getView(returnUrl);
			if (view != null) {
				return view;
			} else {
				return "login";
			}
		}
		writeCookieErrorRemaining(null, request, response, model);

		if (!StringUtils.isBlank(returnUrl)) {
			model.addAttribute(RETURN_URL, returnUrl);
		}
		if (!StringUtils.isBlank(message)) {
			model.addAttribute(MESSAGE, message);
		}
		return "login";
	}



	/**
	 * 用户登陆
	 * 
	 * @param username
	 * @param password
	 * @param captcha
	 * @param processUrl
	 * @param returnUrl
	 * @param message
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public String loginSubmit(String username, String password, String captcha,
			String processUrl, String returnUrl, String message,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		
			try {
				String ip = RequestUtils.getIpAddr(request);
				tuserService.login(request, username, password);
				removeCookieErrorRemaining(request, response);
				String view = getView(returnUrl);
				// cmsLogMng.loginSuccess(request, user,
				// "login.log.loginSuccess");
				if (view != null) {
					return view;
				} else {
					return "redirect:index.do";
				}
			} catch (UsernameNotFoundException e) {
//				errors.addErrorString(e.getMessage());
				// cmsLogMng.loginFailure(request, "login.log.loginFailure",
				// "username=" + username + ";password=" + password);
			} catch (BadCredentialsException e) {
//				errors.addErrorString(e.getMessage());
				// cmsLogMng.loginFailure(request, "login.log.loginFailure",
				// "username=" + username + ";password=" + password);
			}
		
		// 登录失败
		writeCookieErrorRemaining(null, request, response, model);
//		errors.toModel(model);
		if (!StringUtils.isBlank(returnUrl)) {
			model.addAttribute(RETURN_URL, returnUrl);
		}
		if (!StringUtils.isBlank(message)) {
			model.addAttribute(MESSAGE, message);
		}
		return "login";
	}


 	/**
	 * 用户表新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("tuserAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		model.addAttribute("tuser", new Tsuser());
	      //查询出所有的角色
	  	List<Tsuser> tusers=troleService.getTroles();
	      model.addAttribute("roleList",tusers);
	      //查询出所有商家
	      Map<String, Object> param = new HashMap<String, Object>();
	      param.put("delFlag", 0);
	      List<Czjbusiness> businesses = troleService.getBussindessALL(param);
	      model.addAttribute("businesses", businesses);	      
      setDict(model);
		return "sys/tuserEdit";
	}
	
 	/**
	 * 用户表新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("tuserPer.do")
	public String tuserPer(HttpServletRequest request, ModelMap model) {
		model.addAttribute("tuser", new Tsuser());
	      //查询出所有的角色
	  	List<Tsuser> tusers=troleService.getTroles();
	      model.addAttribute("roleList",tusers);
	      //查询出所有商家
	      Map<String, Object> param = new HashMap<String, Object>();
	      param.put("delFlag", 0);
	      List<Czjbusiness> businesses = troleService.getBussindessALL(param);
	      model.addAttribute("businesses", businesses);	      
    setDict(model);
		return "sys/per";
	}	
	

	/**
	 * 用户表保存
	 * 
	 * @param tuser
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("tuserSave.do")
	public String save(Tsuser tuser,String[] businessIds, HttpServletRequest request, ModelMap model) throws Exception{
//		WebErrors errors = validateSave(tuser, request);
//		if (errors.hasErrors()) {
//			return errors.showErrorPage(model);
//		}
      
		
		String pwd=tuser.getPasswd();
		String uid=tuser.getUserid();
		
		try {
			if(tuser.getUserid()!=null&&!tuser.getUserid().equals("")){
				// 编辑
				tuserService.updateTuser(tuser);
				tuserroleService.deleteTuserroleByUserid(tuser.getUserid());
				String [] roleIds= request.getParameterValues("roleIds");
				if (roleIds != null) {
					for (String id : roleIds) {
						Tuserrole tuserrole=new Tuserrole();
						tuserrole.setRoleid(id);
						tuserrole.setUserid(tuser.getUserid());
						tuserroleService.insertTuserrole(tuserrole);
					}
				}
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑用户表", "userid="+tuser.getUserid()));
			} else {
				// 新增
				tuser.setRegtime(new Date());
				tuserService.insertTuser(tuser);
				String [] roleIds= request.getParameterValues("roleIds");
				if (roleIds != null) {
					for (String id : roleIds) {
						Tuserrole tuserrole=new Tuserrole();
						tuserrole.setRoleid(id);
						tuserrole.setUserid(tuser.getUserid());
						tuserroleService.insertTuserrole(tuserrole);
					}
				}
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增用户表", "userid="+tuser.getUserid()));
			}
			
			if(businessIds!=null){
				for(String id : businessIds){
					Czjbusiness czjbusiness = new Czjbusiness();
					czjbusiness.setId(id);
					czjbusiness.setUsername(tuser.getUserid());
					czjbusiness.setDelFlag(1);
					troleService.updateBussiness(czjbusiness);
				}
			}
			
   		} catch (Exception e) {
   			log.error("tuser save error:", e); 
            throw e;
   		}
		if(uid!=null&&!uid.equals("")){
			if("".equals(pwd) || null==pwd){
				return "redirect:tuserList.do";
			}else{
				return "redirect:tuserList.do"; 
			}
		}else{
			return "redirect:tuserList.do";
		}
		
      
	
	}

	/**
	 * 用户表删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("tuserDelete.do")
	public String delete(@RequestParam("ids") List<String> useridList) throws Exception{
		try {
         if (useridList != null) {
   			tuserService.deleteTuser(useridList);
   		}
         } catch (Exception e) {
   			log.error("tuser delete error:", e); 
            throw e;
   		}
		return "redirect:tuserList.do";
	}
	 
	/**
	 * 用户表编辑页面
	 * 
	 * @param userid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("tuserEdit.do")
	public String edit(String userid, HttpServletRequest request, ModelMap model) throws Exception{
      try {
   		Map<String, Object> param = new HashMap<String, Object>();
   		param.put("userid", userid);
         Tsuser tuser = tuserService.getTuser(param);
   		model.addAttribute("tuser", tuser);
   		//查询出用户所对应得角色ID
   	  List<String> rids=tuserroleService.findTrolesByuserId(tuser.getUserid());
      model.addAttribute("roleIds", rids);
      //查询出所有的角色
  	List<Tsuser> tusers=troleService.getTroles();
      model.addAttribute("roleList",tusers);
      //查询出用户所对应得商家ID
      List<String> busids = tuserroleService.findBussinessByuserId(tuser.getUserid());
      model.addAttribute("busIds", busids);
      //查询出所有商家
      Map<String, Object> param1 = new HashMap<String, Object>();
      param1.put("delFlag", 0);
      List<Czjbusiness> businesses = troleService.getBussindessALL(param1);
      model.addAttribute("businesses", businesses);
      
         model.addAttribute("actionEdit", request.getParameter("actionEdit"));
         setDict(model);
         } catch (Exception e) {
   			log.error("tuser edit error:", e); 
            throw e;
   		}
		return "sys/tuserEdit";
	}

	/**
	 * 用户表详情
	 * 
	 * @param userid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("tuserDetail.do")
	public String detail(String userid, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
      try {
      		Map<String, Object> param = new HashMap<String, Object>();
      		param.put("userid", userid);
            Tsuser tuser = tuserService.getTuser(param);
      		model.addAttribute("tuser", tuser);
      		
       		//查询出用户所对应得角色ID
         	  List<String> rids=tuserroleService.findTrolesByuserId(tuser.getUserid());
            model.addAttribute("roleIds", rids);
            //查询出所有的角色
        	List<Tsuser> tusers=troleService.getTroles();
            model.addAttribute("roleList",tusers);
            setDict(model);
            } catch (Exception e) {
   			log.error("tuser detail error:", e); 
            throw e;
   		  }
		return "sys/tuserView";
	}
	 
	/**
	 * 用户表查询（分页）
	 * 
	 * @param tuser
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("tuserList.do")
	public String listPage(Tsuser tuser, Integer pageNo, String order,
			String sort,HttpServletRequest request, ModelMap model) throws Exception{
      try {   
   		if (pageNo == null)
   			pageNo = 1;
         Pagination pagination = tuserService.getTuserList(toMap(tuser), 20, pageNo,
   				order, sort);
         if(tuser.getUsername()!=null && !"".equals(tuser.getUsername())){
        	 request.setAttribute("username", tuser.getUsername());
         }
         if(tuser.getTruename()!=null && !"".equals(tuser.getTruename())){
        	 request.setAttribute("truename", tuser.getTruename());
         }
         if(tuser.getPhone()!=null && !"".equals(tuser.getPhone())){
        	 request.setAttribute("phone", tuser.getPhone());
         }
   		model.addAttribute("pagination", pagination);
         setDict(model);
         } catch (Exception e) {
			log.error("tuser listPage error:", e); 
         throw e;
		   }
		return "sys/tuserList";
	}
	 
	/**
	 * 用户表查询
	 * 
	 * @param tuser
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("tuserList1.do")
	public String list(Tsuser tuser, HttpServletRequest request, ModelMap model) throws Exception{
      try {
   		Map<String,Object> map = tuserService.getTuserList(toMap(tuser));
   		model.addAttribute("list", map.get("rows"));
   		model.addAttribute("total", map.get("total"));
         setDict(model);
         } catch (Exception e) {
   			log.error("tuser list error:", e); 
            throw e;
   		}
		return "sys/tuserList";
	}
	 
	@RequestMapping("validateName.do")
	public void validateName(String username, HttpServletRequest request, HttpServletResponse response,ModelMap model) throws Exception{
      try {
   		boolean isTrue= tuserService.getTuserByName(username);
   		Map<String,Object> map=new HashMap<String, Object>();
   		map.put("isTrue", isTrue);
//   		responseResult(1,"","", map, response);
         } catch (Exception e) {
   			log.error("tuser list error:", e); 
            throw e;
   		}
	}

 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param tuser
	 * @return
	 */	private Map<String,Object> toMap(Tsuser tuser){
	
		return ConvertObj.toMap(tuser);
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
		
	}




	 

//	private WebErrors validateLogin(String username, String password,
//			String captcha, Integer errorRemaining, HttpServletRequest request,
//			HttpServletResponse response) {
//		WebErrors errors = WebErrors.create(request);
//		if (errors.ifOutOfLength(username, "username", 1, 100)) {
//			return errors;
//		}
//		if (errors.ifOutOfLength(password, "password", 1, 32)) {
//			return errors;
//		}
//		// 如果输入了验证码，那么必须验证；如果没有输入验证码，则根据当前用户判断是否需要验证码。
//		if (!StringUtils.isBlank(captcha)
//				|| (errorRemaining != null && errorRemaining < 0)) {
//			if (errors.ifBlank(captcha, "captcha", 100)) {
//				return errors;
//			}
//			try {
//				if (!imageCaptchaService.validateResponseForID(request
//						.getSession().getId(), captcha)) {
//					errors.addError("error.invalidCaptcha");
//					return errors;
//				}
//			} catch (CaptchaServiceException e) {
//				errors.addError("error.exceptionCaptcha");
//				log.warn("", e);
//				return errors;
//			}
//		}
//		return errors;
//	}
	private void writeCookieErrorRemaining(Integer userErrorRemaining,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		// 所有访问的页面都需要写一个cookie，这样可以判断已经登录了几次。
		Integer errorRemaining = getCookieErrorRemaining(request, response);
		Integer errorInterval = 30;
		if (userErrorRemaining != null
				&& (errorRemaining == null || userErrorRemaining < errorRemaining)) {
			errorRemaining = userErrorRemaining;
		}
		int maxErrorTimes = 3;
		if (errorRemaining == null || errorRemaining > maxErrorTimes) {
			errorRemaining = maxErrorTimes;
		} else if (errorRemaining <= 0) {
			errorRemaining = 0;
		} else {
			errorRemaining--;
		}
		model.addAttribute("errorRemaining", errorRemaining);
		CookieUtils.addCookie(request, response, COOKIE_ERROR_REMAINING,
				errorRemaining.toString(), errorInterval * 60, null);
	}
	private void removeCookieErrorRemaining(HttpServletRequest request,
			HttpServletResponse response) {
		CookieUtils.cancleCookie(request, response, COOKIE_ERROR_REMAINING,
				null);
	}

	private Integer getCookieErrorRemaining(HttpServletRequest request,
			HttpServletResponse response) {
		Cookie cookie = CookieUtils.getCookie(request, COOKIE_ERROR_REMAINING);
		if (cookie != null) {
			String value = cookie.getValue();
			if (NumberUtils.isDigits(value)) {
				return Integer.parseInt(value);
			}
		}
		return null;
	}

	/**
	 * 获得返回页面
	 * 
	 * @return
	 */
	private String getView(String returnUrl) {
		if (!StringUtils.isBlank(returnUrl)) {
			StringBuilder sb = new StringBuilder("redirect:");
			sb.append(returnUrl);
			return sb.toString();
		} else {
			return null;
		}
	}
	@Resource
	private TuserService tuserService;
	@Resource
	private TuserroleService tuserroleService;
	@Resource
	private TroleService troleService;
//	@Autowired
//	private ImageCaptchaService imageCaptchaService;
//	@Autowired
//	private CookieLocaleResolver resolver;
}